package com.hzw.service.impl;

import com.hzw.bean.FriendsRelation;
import com.hzw.dao.FriendsRelationMapper;
import com.hzw.dao.UserMapper;
import com.hzw.service.FriendsRelationService;
import com.hzw.utils.UUIDUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * Created by Administrator on 2019/4/3.
 */
@Service
public class FriendsRelationServiceImpl implements FriendsRelationService {
    @Resource
    private FriendsRelationMapper friendsRelationMapper;
    @Resource
    private UserMapper userMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addFocus(FriendsRelation friendsRelation) {
        //先根据用户id和目标id查询是否存在此关系
        String userId = friendsRelation.getUserId();
        String targetId = friendsRelation.getTargetId();
        FriendsRelation friendsRelation1 = friendsRelationMapper.selectByTwoId(userId,targetId);
        if(friendsRelation1 == null){  //不存在则新插入一条
            //关注好友，在好友关系表里插入一条记录
            String id = UUIDUtils.getUUID();
            friendsRelation.setId(id);
            friendsRelationMapper.insertSelective(friendsRelation);
        }else {
            friendsRelation1.setDelFlag(0);
            friendsRelationMapper.updateByPrimaryKeySelective(friendsRelation1);
        }


        //修改自己的关注数+1
        userMapper.updateFocusNum(friendsRelation.getUserId(),1);
        //修改被关注人的粉丝数+1
        userMapper.updateFollowNum(friendsRelation.getTargetId(),1);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelFocus(FriendsRelation friendsRelation) {
        //软删除好友关系表里的数据
        String userId = friendsRelation.getUserId();
        String targetId = friendsRelation.getTargetId();
        friendsRelationMapper.deleteByUserAndTargetId(userId,targetId);

        //修改自己的关注数-1
        userMapper.updateFocusNum(friendsRelation.getUserId(),-1);
        //修改被关注人的粉丝数-1
        userMapper.updateFollowNum(friendsRelation.getTargetId(),-1);
    }

    @Override
    public int getFocusFlag(String userId, String targetId) {
        FriendsRelation friendsRelation = friendsRelationMapper.selectByTwoId(userId,targetId);
        int foucusFlag = 0;
        if(friendsRelation != null){
            int delFlag = friendsRelation.getDelFlag();
            if(delFlag == 0){  //软删除标记为0代表已关注，将foucusFlag设为1
                foucusFlag = 1;
            }
        }
        return foucusFlag;
    }


}
